package com.huwaiwai001.echo.nio.server;

import com.huwaiwai001.echo.constant.ServerInfo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by hww on 2019/3/18 14:06.
 */
public class EchoNioServerHandler implements AutoCloseable {

    private ExecutorService executorService;
    private ServerSocketChannel serverSocketChannel;
    private Selector selector;


    EchoNioServerHandler() throws IOException {
        this.executorService = Executors.newFixedThreadPool(5);
        this.serverSocketChannel = ServerSocketChannel.open();
        this.serverSocketChannel.configureBlocking(false);
        this.serverSocketChannel.bind(new InetSocketAddress(ServerInfo.ECHO_PORT));
        this.selector = Selector.open();
        this.serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务器端程序启动，该程序在" + ServerInfo.ECHO_PORT + "端口上进行监听...");
    }

    public void handle() throws Exception {
        while (selector.select() > 0) {
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isAcceptable()) {
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    if (socketChannel != null) {
                        EchoNioServerTask task = new EchoNioServerTask(socketChannel);
                        executorService.execute(task);
                    }
                }
                // 移除当前通道
                iterator.remove();
            }
        }
    }

    @Override
    public void close() throws Exception {
        executorService.shutdown();
        serverSocketChannel.close();
    }
}
